var request = require("request");
var fs = require("fs");
var moment = require('moment');
var cheerio = require("cheerio");

async function getHtml(page){
    return new Promise((resolve,reject)=>{
        request({
            url:`https://www.bingimg.cn/list${page}`,
            headers:{
                "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"
            }
        },(err,response,body)=>{
            
            if (!err && response.statusCode == 200) { 
                resolve(body);
            }
            else
            {
                reject()
            }
        })
    })
}

(async ()=>{

    if(!fs.existsSync('./hdImgs')){
        fs.mkdirSync('./hdImgs')
    }

    for(var page=1;page<171;page++){
        let html = await getHtml(page);
        var $ = cheerio.load(html);
        let eles = $(".col-xs-12.col-sm-6.col-md-4.col-md-4");
        for(var i=0;i<eles.length;i++){
            let item = eles.eq(i);
            let url = item.find('.card_img').attr('src');

            let info = {
                title: item.find('.card_img').attr('alt'),
                url,
                page,
                date: item.find('.card_date_div .card_foot').eq(0).text(),
            }


            var links = item.find('.card_date_div a');
            for(var linkIndex=0;linkIndex<links.length;linkIndex++){
                let item = links.eq(linkIndex);
                info.url = item.attr('href');
            }
            
            await downloadUrl(info);
        }
    }
})(); 

async function downloadUrl(info){
    return new Promise((resolve,reject)=>{
        let date =  moment(info.date).format("YYYYMMDD");
        let filename = date+".jpg";
        request({
            url: date < 20180911 ? info.url : getBingUrl(info.url),
            headers:{
                "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"
            }
        }).pipe(
            fs.createWriteStream(`./hdImgs/${filename}`).on('close',err=>{  
                if(err){
                    console.log('写入失败',err)
                    reject();
                }
                else
                {
                    console.log(`page:${info.page} ${filename} 写入成功`);
                    resolve();
                }
            })
        )
    })
}

function getBingUrl(url)
{
    return 'https://cn.bing.com/th?id='+/OHR(.*)/.exec(url)[0]
}